<?php
declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use think\facade\Queue;
use app\job\Job1;
use app\api\model\ZhChat as ZhChatModel;
use app\api\model\ZhChatLog as ZhChatLogModel;
use utils\wechart\TemplateService;
use app\backend\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;


class Swoole extends Command
{
	protected function configure()
	{
		$this->setName('swoole')
		     ->setDescription('swooleServer');
       
	}
	
	protected function execute(Input $input, Output $output)
	{
		$ws = new \Swoole\WebSocket\Server('0.0.0.0', 9502);

		
		$ws->on('open', function ($ws, $request) {
			//			$data = json_decode($request->data, true);
			//			cache([]);
			echo '连接成功';
			$ws->push($request->fd, json_encode(['msg' => '连接成功', 'fid' => $request->fd]));
		});
		
		$ws->on('message', function ($ws, $request) {
			
			$data = json_decode($request->data, true);
			if ($data['type'] == 'heartbeat') {
                $userList = cache('chat_user_' . $data['userUid']);
                
				if($userList != $request->fd){
                    cache('chat_user_' . $data['userUid'],$request->fd);
                    
                    $userFDData =  Db::name('zh_fd')->where([
                                                                'wxapp_id'=> $data['wxapp_id'],
                                                                'u_id'    => $data['userUid']
                                                            ])->find();
                    
                    if($userFDData && $userFDData['fd'] != $request->fd){
                        Db::name('zh_fd')->where([
                                                        'wxapp_id'=> $data['wxapp_id'],
                                                        'u_id'    => $data['userUid']
                                                    ])->update(['fd'=> $request->fd]);
                    }elseif (!$userFDData){
                        Db::name('zh_fd')->where([
                                                    'wxapp_id'=> $data['wxapp_id'],
                                                    'u_id'    => $data['userUid']
                        ])->insert([
                            'wxapp_id'   => $data['wxapp_id'],
                            'u_id'       => $data['userUid'],
                            'fd'         => $request->fd,
                            'create_time'=> date('Y-m-d H:i:s',time())
                        ]);
                    }
                }
				$ws->push($request->fd, json_encode(['type' => $data['type'], 'msg' => '心跳', 'data' => $userList, 'fid' => $request->fd]));
				
			} else if ($data['type'] == 'msg') {
                
                //判断在线不在线
                $sFD = Db::name('zh_fd')->where([
                    'wxapp_id'=> $data['wxapp_id'],
                    'u_id'    => $data['data']['msg']['suserinfo']
                ])->value('fd');
                if($sFD && $ws->isEstablished($sFD)){
                    //在线就推送然后存聊天消息的记录
                    $ws->push($sFD, json_encode($data));
                    $data['is_read'] = 1;
                }else{
                    $data['is_read'] = 0;
                    
                    $TemplateService = new TemplateService();
                    $sUserData = MemberModel::where(['uid' => $data['data']['msg']['suserinfo'], 'wxapp_id' => $data['wxapp_id']])->find();
                    $wxSetting    = SysSiteModel::where('wxapp_id',$data['wxapp_id'])->find();
    
                    if($sUserData){
                        $moban = [
                            'thing1' => [
                                'value' => $sUserData['nickname'],
                            ],
                            'thing4' => [
                                'value' => '您收到一条消息',
                            ],
                            'time3' => [
                                'value' => date('Y-m-d H:i:s',time()),
                            ],
                        ];
                        $a =  $TemplateService->sendSubscribeMessage(['wxapp_id'=> $data['wxapp_id'],'openid'=> $sUserData['openid'],'template_id'=> $wxSetting['chat_template_id'],'data'=> $moban]);
        
                    }
                }
                
                file_put_contents('job.txt',$sFD);
                Queue::push(Job1::class,$data);
                // 没在线直接存

//				$to_fd = cache('chat_user_' . $data['touser']);
//				$ws->push(intval($to_fd), json_encode([
//					'type' => $data['type'],
//					'msg'  => '收到消息',
//					'data' => $data,
//					'fid'  => $request->fd,
//					'to'   => $to_fd
//				]));
			}
			//			if(){
			//
			//			}
			
		});
		
		$ws->on('close', function ($ws, $fd) {
			$userList = cache('chat_user_list') ?: [];
			
			$userList = $this->delByValue($userList,$fd);
			cache('chat_user_list',$userList);
		});
		cache('chat_user_list',[]);
		$ws->start();
		
		$output->writeln("start swoole");
		
	}
	
	function delByValue($arr, $value)
	{
		$keys = array_keys($arr, $value);
		if (!empty($keys)) {
			foreach ($keys as $key) {
				unset($arr[$key]);
			}
		}
		return $arr;
	}
	
}
